/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.parser;

import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.business.Service;
import com.anhndt.audiobook.utils.DialogUtil;
import com.sun.lwuit.util.Log;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;

/**
 *
 * @author Anhndt
 */
public class WebServicesParser {

    private Service service;
    public WebServicesParser(Service service) {
        this.service = service;
    }

    public SoapObject getResponse() throws Exception {
        return getResponse(true);
    }

    public SoapObject getResponse(boolean receiveResponse) throws Exception {
        System.out.println("[WebServicesParser] call service : " + service.getUrl());
        SoapObject response = null;
        CustomHttpTransport transport = null;
        SoapSerializationEnvelope envelope = null;
        try {
            envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(service.getRequest());
            transport = new CustomHttpTransport(service.getUrl());
            transport.call(service.getSoapAction(), envelope);
            if (receiveResponse) {
                response = (SoapObject) envelope.getResponse();
            }
        } catch (SecurityException se) {
            se.printStackTrace();
            DialogUtil.showWarningAuthorizeNetwork();
        } catch(SoapFault s){
            s.printStackTrace();
            throw new Exception(Resource.TXT_ERROR_CONNECT_TO_SERVER);
        }catch (IOException se) {
            se.printStackTrace();
            DialogUtil.showErrorCheckNetword();
        } finally {
            if (transport != null) {
                transport = null;
            }
            service = null;
            if (envelope != null) {
                envelope = null;
            }
        }
        return response;
    }

    public String getProperty(SoapObject soap, String key) {
        try {
            return soap.getProperty(key).toString();
        } catch (Exception e) {
            return null;
        }
    }
}
